/*
 * @Author: NJ_1098 xiabaoxin
 * @Date: 2025-02-13 11:02:30
 * @LastEditors: NJ_1098 xiabaoxin
 * @LastEditTime: 2025-02-13 16:45:25
 * @Description: 日志配置
 */
const log4js = require("log4js");
const fs = require("fs");
const path = require("path");

const levels = {
  trace: log4js.levels.TRACE,
  debug: log4js.levels.DEBUG,
  info: log4js.levels.INFO,
  warn: log4js.levels.WARN,
  error: log4js.levels.ERROR,
  fatal: log4js.levels.FATAL,
};

log4js.configure({
  appenders: {
    console: { type: "console" },
    info: {
      type: "file",
      filename: "logs/info.log",
    },
    error: {
      type: "dateFile",
      filename: "logs/error",
      pattern: "yyyyMMdd.log",
      alwaysIncludePattern: true,
    },
  },
  categories: {
    default: { appenders: ["console"], level: "debug" },
    info: {
      appenders: ["info", "console"],
      level: "info",
    },
    error: {
      appenders: ["error", "console"],
      level: "error",
    },
  },
});

exports.debug = (content) => {
  //注意：每次都要重新获取log4js.getLogger('debug')级别才能生效
  let logger = log4js.getLogger("debug");
  logger.level = levels.debug;
  logger.debug(content);
};

const info = (content) => {
  let logger = log4js.getLogger("info");
  logger.level = levels.info;
  logger.info(content);
};

exports.info = info;

exports.warn = (content) => {
  let logger = log4js.getLogger("warn");
  logger.level = levels.warn;
  logger.warn(content);
};

const error = (content) => {
  let logger = log4js.getLogger("error");
  logger.level = levels.error;
  logger.error(content);
};

exports.error = error;

/**
 * @author: NJ_1098 xiabaoxin
 * @description: 清空或删除日志文件
 * @param {*} startName 文件开头
 * @param {*} needs 文件删除标识
 * @return {*}
 */
exports.clearOrDeleteOldLogFilesByNeeds = (startName, needs) => {
  const logDir = "logs";
  fs.readdir(logDir, (err, files) => {
    if (err) {
      console.error("读取日志目录时出错:", err);
      return;
    }
    files.forEach((file) => {
      if (
        file.startsWith(startName ? startName : "info") &&
        file.endsWith(".log")
      ) {
        const filePath = path.join(logDir, file);
        fs.writeFile(filePath, "", (err) => {
          if (err) {
            error(`清空日志文件${file}出错：`, err);
          } else {
            if (needs) {
              fs.unlink(filePath, (unlinkErr) => {
                if (unlinkErr) {
                  error(`删除日志文件 ${file} 时出错:`, unlinkErr);
                } else {
                  info(`日志文件 ${file} 已删除`);
                }
              });
            } else {
              info(`日志文件 ${file} 已清空`);
            }
          }
        });
      }
    });
  });
};
